-- local name = "car"
local name = arg[1]
local path = "\"E:\\Programs\\STMicroelectronics\\STM32 ST-LINK Utility\\ST-LINK Utility\\ST-LINK_CLI.exe\""
local sn = "E1007200D0D2139393740544"
-- sn = "19002300072D373637365744"

local info = function(str) print("[INFO] "..str) end
local error = function(str) print("[ERROR] "..str) os.exit(1) end

info("开始构建项目: "..name)

---------------------------------------------
-- [[         build directories         ]] --
---------------------------------------------
info("创建文件夹")

local io = require("io")
-- 检查build目录是否存在
if not io.open("build", "r") then
  -- 如果build目录不存在，则创建build目录
  os.execute("mkdir build")
end

-- 检查bin目录是否存在
if not io.open("bin", "r") then
  -- 如果bin目录不存在，则创建bin目录
  os.execute("mkdir bin")
end

---------------------------------------------
-- [[           build build             ]] --
---------------------------------------------
info("编译")

-- 执行cmake命令
if (not os.execute("cmake -DPROJECT_NAME="..name.." -Bbuild -G \"MinGW Makefiles\" -S .")) then
  error("cmake失败")
end
-- 执行mingw32-make命令
if (not os.execute("mingw32-make -C build -f Makefile")) then
  error("make失败")
end

---------------------------------------------
-- [[           build bin             ]] --
---------------------------------------------
info("整理二进制文件")

if (not os.execute("copy build\\"..name..".bin bin\\"..name..".bin")) then
  error("整理bin文件失败")
end

if (not os.execute("copy build\\"..name..".elf bin\\"..name..".elf")) then
  error("整理elf文件失败")
end

if (not os.execute("copy build\\"..name..".hex bin\\"..name..".hex")) then
  error("整理hex文件失败")
end

---------------------------------------------
-- [[               burn                ]] --
---------------------------------------------
info("烧录")

-- 列举检测到的ST-Link设备
if (not os.execute("\""..path.."\"".." -List")) then
  error("未检测到ST-Link设备")
end
-- 清空读写保护，一般用不到
-- os.execute(path.." -c SN="..sn.." SWD UR -OB RDP=0 IWDG_SW=1 nRST_STOP=1 nRST_STDBY=1 Data0=0xFF Data1=0xFF WRP=0xFFFFFFFF")
-- 擦除前64页flash，逐页擦除非常慢，一般不使用
-- os.execute(path.." -c SN="..sn.." SWD UR LPM -SE 0 63")
-- 擦除全部flash
if (not os.execute(path.." -c SN="..sn.." SWD UR LPM -ME")) then
  error("擦除失败")
end
-- bin烧录
if (not os.execute(path.." -c SN="..sn.." SWD UR LPM -P build/"..name..
      ".bin 0X08000000 -V after_programming")) then
  error("烧录失败")
end
-- 复位
if (not os.execute(path.." -c SN="..sn.." -Rst")) then
  error("复位失败")
end

---------------------------------------------
-- [[               done                ]] --
---------------------------------------------
info("所有任务全部完成")
